package com.example.zhaoping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhaoping.domain.ResponseResult;
import com.example.zhaoping.domain.User;
import com.example.zhaoping.dto.UserRegisterDto;
import com.example.zhaoping.enums.AppHttpCodeEnum;
import com.example.zhaoping.exception.SystemException;
import com.example.zhaoping.mapper.UserMapper;
import com.example.zhaoping.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhaoping.utils.BeanCopyUtils;
import com.example.zhaoping.utils.JwtUtils;
import com.example.zhaoping.vo.PageVo;
import com.example.zhaoping.vo.UserInfoVo;
import com.example.zhaoping.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author czx
 * @since 2024-12-23
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
//    ================================登录模块================================
    @Override
    public UserLoginVo login(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = getOne(queryWrapper);
        if(!StringUtils.hasText(username)){
            // 提示'必须要传用户名'。AppHttpCodeEnum是我们写的枚举类。SystemException是我们写的统一异常处理的类
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        //用户不存在
        if(user==null){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }

        //密码不存在
        if(!StringUtils.hasText(password)){
            // 提示'必须要传用户名'。AppHttpCodeEnum是我们写的枚举类。SystemException是我们写的统一异常处理的类
            throw new SystemException(AppHttpCodeEnum.REQUIRE_PASSWORD);
        }
        //角色不是管理员，不能登录
        if(user.getRole()!=1){
            throw new SystemException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //密码不对
        if(!user.getPassword().equals(password)){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }

            UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
            //使用jwt 生成token
            Map<String, Object> claims = new HashMap<>();
            //放usernaem
            claims.put("username",username);
            claims.put("userid",user.getId());
            String jwt = JwtUtils.generateJwt(claims);
//            log.info("token生成成功 {}",jwt);
//        放进redis
        stringRedisTemplate.opsForValue().set("login:"+user.getId(),jwt,12, TimeUnit.HOURS);
            return new UserLoginVo(jwt,userInfoVo);


    }

    //    ================================注册模块================================

    @Override
    public ResponseResult register(UserRegisterDto userInfoVo) {
        User user = BeanCopyUtils.copyBean(userInfoVo, User.class);
        if (user.getUsername()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        if (user.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_PASSWORD);
        }
        if (user.getEmail()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_EMAIL);
        }
        if (user.getPhoneNumber()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_PHONENUMBER);
        }
        if (user.getFullName()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_FULLNAME);
        }

        if (user.getSex()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_SEX);
        }
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());
        //查数据库看有没有相同的用户名
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        User one = getOne(queryWrapper);
        if(one!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //查数据库看有没有相同的手机号码
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhoneNumber,user.getPhoneNumber());
        User phoneuser = getOne(wrapper);
        if(phoneuser!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }

        // 查数据库看有没有相同的电子邮件
        LambdaQueryWrapper<User> emailQueryWrapper = new LambdaQueryWrapper<>();
        emailQueryWrapper.eq(User::getEmail, user.getEmail());
        User existingUserByEmail = getOne(emailQueryWrapper);
        if (existingUserByEmail != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.EMAIL_EXIST);  // 假设你有一个对应的枚举值
        }




        if(save(user)){
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.REGISTER_ERROR);

    }

    //    ================================分页查询用户模块================================

    @Override
    public ResponseResult userList(Integer pageNum, Integer pageSize, String username) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(username),User::getUsername,username);

        Page<User> page = new Page<>(pageNum,pageSize);
        Page<User> articlePage = page(page, queryWrapper);
        List<User> records = articlePage.getRecords();

        PageVo pageVo = new PageVo(records, articlePage.getTotal());
        return ResponseResult.okResult(pageVo);



    }

    //    ================================重新设置密码模块================================


    @Override
    public ResponseResult resetPassword(Map map) {
//        把字符串转换成long
        Long id = Long.parseLong(map.get("id").toString());

        String password = (String) map.get("password");
        if (id == null ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        if (password == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_PASSWORD);
        }
        User user = getById(id);
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_NOT_EXIST);
        }
        user.setPassword(password);
        if (updateById(user)) {
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);


    }

    //    ================================管理员用户注册================================


    @Override
    public ResponseResult userregister(UserRegisterDto userRegisterDto) {
        User user = BeanCopyUtils.copyBean(userRegisterDto, User.class);
//        查看数据库是否有相同的用户名
        if (getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername())) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, user.getEmail())) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.EMAIL_EXIST);
        }
        if (getOne(new LambdaQueryWrapper<User>().eq(User::getPhoneNumber, user.getPhoneNumber())) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        user.setRole(1);
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());
        if (save(user)) {
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.REGISTER_ERROR);
    }
}
